<template>
  <div class="subject-manage">

    <!-- 标题和操作按钮区 -->
    <div class="header">
      <div class="left">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>新增学科
        </el-button>
      </div>
      <div class="right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索学科名称"
          class="search-input"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 学科列表 -->
    <div class="subject-list">
      <el-row :gutter="20">
        <el-col :span="8" v-for="subject in subjects" :key="subject.id">
          <el-card class="subject-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="subject-name">{{ subject.name }}</span>
                <div class="operations">
                  <el-button type="primary" link @click="goToLibrary(subject)">
                    <el-icon><Management /></el-icon>题库管理
                  </el-button>
                  <el-dropdown>
                    <el-button link>
                      <el-icon><More /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="showEditDialog(subject)">
                          <el-icon><Edit /></el-icon>编辑
                        </el-dropdown-item>
                        <el-dropdown-item @click="handleDelete(subject)" class="delete-item">
                          <el-icon><Delete /></el-icon>删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </template>
            <div class="subject-info">
              <p class="description">{{ subject.description || '暂无描述' }}</p>
              <div class="meta-info">
                <span>创建时间：{{ subject.createdAt }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[8, 16, 24, 32]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增学科' : '编辑学科'"
      width="500px"
    >
      <el-form
        ref="subjectFormRef"
        :model="subjectForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="学科名称" prop="name">
          <el-input v-model="subjectForm.name" placeholder="请输入学科名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="subjectForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入学科描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SubjectView">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, More, Management, Search } from '@element-plus/icons-vue'
import { getSubjects, createSubject, updateSubject, deleteSubject } from '@/api/subject'
// import { formatDate as formatDateUtil } from '@/utils/format'

const router = useRouter()
const subjects = ref([])
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')
const subjectFormRef = ref(null)
const subjectForm = ref({
  id: null,
  name: '',
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入学科名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

const searchKeyword = ref('')
const allSubjects = ref([])

// 格式化日期
// const formatDate = (date) => {
//   return formatDateUtil(date)
// }

// 获取学科列表
const fetchSubjects = async () => {
  try {
    const userId = JSON.parse(localStorage.getItem('user')).id
    const res = await getSubjects(userId, currentPage.value, pageSize.value)
    allSubjects.value = res.data.list
    total.value = res.data.total
    handleSearch()
  } catch (error) {
    ElMessage.error('获取学科列表失败')
  }
}

// 搜索处理
const handleSearch = () => {
  if (!searchKeyword.value) {
    subjects.value = allSubjects.value
    return
  }
  subjects.value = allSubjects.value.filter(subject => 
    subject.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    (subject.description && subject.description.toLowerCase().includes(searchKeyword.value.toLowerCase()))
  )
}

// 显示新增对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  subjectForm.value = {
    id: null,
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (subject) => {
  dialogType.value = 'edit'
  subjectForm.value = {
    id: subject.id,
    name: subject.name,
    description: subject.description
  }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!subjectFormRef.value) return
  await subjectFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const userId = JSON.parse(localStorage.getItem('user')).id
        if (dialogType.value === 'add') {
          await createSubject(userId, subjectForm.value.name, subjectForm.value.description)
          ElMessage.success('创建成功')
        } else {
          await updateSubject(subjectForm.value.id, subjectForm.value.name, subjectForm.value.description)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchSubjects()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '创建失败' : '更新失败')
      }
    }
  })
}

// 删除学科
const handleDelete = (subject) => {
  ElMessageBox.confirm(
    '确定要删除该学科吗？删除后将无法恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteSubject(subject.id)
      ElMessage.success('删除成功')
      fetchSubjects()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 跳转到题库管理
const goToLibrary = (subject) => {
  router.push({
    path: `/question`,
    query: { subjectId: subject.id, subjectName: subject.name }
  })
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchSubjects()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchSubjects()
}

onMounted(() => {
  fetchSubjects()
})
</script>

<style scoped>
.subject-manage {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header .left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header .right {
  display: flex;
  align-items: center;
}

.search-input {
  width: 250px;
}

.subject-list {
  margin-top: 20px;
}

.subject-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.subject-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.subject-name {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.operations {
  display: flex;
  gap: 8px;
}

.subject-info {
  color: #606266;
}

.description {
  margin: 10px 0;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.meta-info {
  font-size: 13px;
  color: #909399;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.delete-item {
  color: #f56c6c;
}

/* :deep(.el-breadcrumb) {
  margin-bottom: 20px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}

:deep(.el-card__body) {
  padding: 15px 20px;
} */
</style> 